/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable array-callback-return */
/* eslint-disable no-restricted-syntax */
/* eslint-disable no-undef */
/* eslint-disable import/order */
/* eslint-disable react/jsx-no-bind */
/* eslint-disable jsx-a11y/anchor-is-valid */
/* eslint-disable no-alert */
/* eslint-disable promise/catch-or-return */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable promise/always-return */
/* eslint-disable eqeqeq */
/* eslint-disable jsx-a11y/click-events-have-key-events */
/* eslint-disable jsx-a11y/no-static-element-interactions */
/* eslint-disable react/prop-types */
/* eslint-disable react/jsx-props-no-spreading */
import React, { useState, memo, useRef, useEffect } from 'react';
import Typography from '@mui/material/Typography';
import IconFont from '@/renderer/components/IconFont';
import Card from '@mui/material/Card';
import CardContent from '@mui/material/CardContent';
import CardMedia from '@mui/material/CardMedia';
import { Button, CardActionArea } from '@mui/material';
import Grid from '@mui/material/Unstable_Grid2';
import Fab from '@mui/material/Fab';
import { useNavigate, Link } from 'react-router-dom';
import {
  ArrowDownOutlined,
  PlusOutlined,
  SearchOutlined,
  DeleteFilled,
  GithubFilled,
} from '@ant-design/icons';
import Modal from '@/renderer/components/Modal';
import Empty from '@/renderer/components/Empty';
import { blue } from '@mui/material/colors';
import TextField from '@mui/material/TextField';
import Chip from '@mui/material/Chip';
import { useAsyncEffect, useRequest } from 'ahooks';
import Box from '@mui/material/Box';
import IconButton from '@mui/material/IconButton';
import Popover from '@mui/material/Popover';
import {
  DndContext,
  useSensor,
  useSensors,
  MouseSensor,
  PointerSensor,
  KeyboardSensor,
  closestCenter,
} from '@dnd-kit/core';
import {
  SortableContext,
  useSortable,
  arrayMove,
  sortableKeyboardCoordinates,
  rectSortingStrategy,
} from '@dnd-kit/sortable';
import { useIdb } from 'react-use-idb';
import { CSS } from '@dnd-kit/utilities';
import { useDispatch } from 'react-redux';
import { change } from '@/renderer/store/snackbar';
import AddProject from './AddProject';
import './index.css';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import 'dayjs/locale/zh-cn';
import fs from 'fs';

dayjs.extend(relativeTime).locale('zh-cn');

const url = '/webtool/v1/project';

const ActionAreaCard = memo(
  ({
    id,
    project_name,
    project_address,
    extra,
    logo_url,
    setmodal,
    created_at,
    value,
    setValue,
  }) => {
    const col = { xs: 6, sm: 6, md: 4, lg: 3, xl: 3, xxl: 2 };
    const navigate = useNavigate();

    const [popover, setpopover] = useState({
      open: false,
      anchorEl: null,
      onClose: () => {
        setpopover((s) => ({ ...s, open: false }));
      },
    });
    const { attributes, listeners, setNodeRef, transform, transition } =
      useSortable({ id });
    const style = {
      transform: CSS.Transform.toString(transform),
      transition,
    };
    return (
      <Grid
        {...col}
        ref={setNodeRef}
        style={style}
        {...attributes}
        {...listeners}
      >
        <Popover
          id={id}
          {...popover}
          anchorOrigin={{
            vertical: 'bottom',
            horizontal: 'right',
          }}
          transformOrigin={{
            horizontal: 'right',
          }}
        >
          <Typography sx={{ p: 2, backgroundColor: '#666666' }}>
            仅删除项目配置,不会删除项目文件{' '}
            <a
              style={{ color: '#ffffff', cursor: 'pointer' }}
              onClick={(e) => {
                const newvalue = value.filter((it) => it.id != id);
                setValue(newvalue);
                localStorage.removeItem(project_name);
              }}
            >
              删除
            </a>
          </Typography>
        </Popover>
        <Card
          sx={{
            display: 'flex',
            cursor: 'pointer',
            borderRadius: 3,
            backgroundColor: '#666666',
            overflow: 'hidden',
          }}
          onClick={() => {
            navigate('/home/projectsetting', {
              replace: false,
              state: { id },
            });
          }}
        >
          <CardMedia
            component="img"
            sx={{
              width: 48,
              height: 48,
              borderRadius: 3,
              margin: '16px 0 0 16px',
            }}
            image={logo_url}
            alt="Live from space album cover"
          />
          <Box
            sx={{
              display: 'flex',
              flex: 1,
              flexDirection: 'column',
              overflow: 'hidden',
            }}
          >
            <CardContent sx={{ flex: '1 0 auto', paddingBottom: 0 }}>
              <Typography component="div" variant="h6" noWrap>
                {project_name}
              </Typography>
              <Typography
                variant="subtitle1"
                color="text.secondary"
                component="div"
                noWrap
                onClick={(e) => {
                  e.stopPropagation();
                  window.open(project_address);
                }}
              >
                <GithubFilled /> {project_address}
              </Typography>
            </CardContent>
            <Box
              sx={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                margin: '0 8px 8px 16px',
              }}
            >
              <span>{dayjs(created_at).fromNow()}</span>
              <IconButton
                aria-label="previous"
                onClick={(e) => {
                  e.stopPropagation();
                  setpopover((s) => ({
                    ...s,
                    open: true,
                    anchorEl: e.currentTarget,
                  }));
                }}
              >
                <DeleteFilled style={{ color: '#f44336' }} />
              </IconButton>
            </Box>
          </Box>
        </Card>
      </Grid>
    );
  }
);

function Homepage() {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const [sort, setsort] = useState(false);
  const [modalprops, setmodal] = useState({
    open: false,
  });
  const ref = useRef();
  const [value, setValue] = useIdb('projects', []);
  const [dragpath, setdragpath] = useState(null);

  const mouseSensor = useSensor(MouseSensor, {
    coordinateGetter: sortableKeyboardCoordinates,
    activationConstraint: {
      distance: 8,
    },
  });

  const sensors = useSensors(
    useSensor(PointerSensor, {
      activationConstraint: {
        distance: 8,
      },
    }),
    useSensor(KeyboardSensor, {
      activationConstraint: {
        distance: 8,
      },
      coordinateGetter: sortableKeyboardCoordinates,
    }),
    mouseSensor
  );

  function handleDragEnd(event) {
    const { active, over } = event;
    if (active.id !== over.id) {
      const itemes = JSON.parse(JSON.stringify(value)) ?? [];
      const keyarr = itemes.map((it) => it.id);
      const oldIndex = keyarr?.indexOf?.(active.id);
      const newIndex = keyarr?.indexOf?.(over.id);
      const newpages = arrayMove(itemes, oldIndex, newIndex);
      setValue(newpages);
    }
  }

  useEffect(() => {
    const allocal = [];
    const curproj = [];
    if (dragpath) {
      value?.map((it) => {
        const pathes = localStorage.getItem(it?.project_name);
        curproj.push({ ...it, path: pathes, projectname: it?.project_name });
        allocal.push(pathes);
      });

      if (allocal.includes(dragpath)) {
        const id = curproj?.filter((it) => it?.path == dragpath)[0]?.id;
        navigate('/home/projectsetting', {
          replace: false,
          state: { id },
        });
        return;
      }

      setmodal((s) => ({
        ...s,
        open: true,
        title: '添加项目',
      }));
    }
  }, [dragpath]);

  useEffect(() => {
    document.addEventListener('drop', (event) => {
      event.preventDefault();
      event.stopPropagation();
      for (const f of event.dataTransfer.files) {
        setdragpath(f.path);
      }
    });
    document.addEventListener('dragover', (e) => {
      e.preventDefault();
      e.stopPropagation();
    });

    document.addEventListener('dragenter', (event) => {
      console.log('File is in the Drop Space');
    });

    document.addEventListener('dragleave', (event) => {
      console.log('File has left the Drop Space');
    });
  }, []);

  return (
    <div
      style={{
        width: '100%',
        position: 'absolute',
        overflow: 'hidden',
        height: '100%',
      }}
    >
      <div style={{ margin: 12, height: '100%' }}>
        <div
          className="centerl"
          style={{
            marginBottom: 12,
            justifyContent: 'space-between',
            userSelect: 'none',
          }}
        >
          <div className="centerl">
            <IconFont
              type="icon-home-fill"
              style={{
                color: 'rgba(255,255,255,0.8)',
                fontSize: 24,
                margin: '0px 6px 0 0',
              }}
            />
            <Typography variant="h6" color="rgba(255,255,255,0.8)" mr={2}>
              主页
            </Typography>
            {modalprops?.filter && (
              <Chip
                icon={<SearchOutlined />}
                size="small"
                label={modalprops.filter}
                color="primary"
                variant="outlined"
                onDelete={() => {
                  setmodal((s) => ({
                    ...s,
                    filter: null,
                  }));
                }}
              />
            )}
          </div>
          <div
            className="center"
            style={{ cursor: 'pointer' }}
            onClick={() => {
              setsort(!sort);
            }}
          >
            <ArrowDownOutlined rotate={sort ? 0 : 180} />
            <span>{sort ? '时间降序' : '时间升序'}</span>
          </div>
        </div>
        <DndContext
          sensors={sensors}
          collisionDetection={closestCenter}
          onDragEnd={handleDragEnd}
          className="columns"
        >
          <Grid container spacing={2}>
            <SortableContext
              items={
                value
                  ? value
                      ?.filter?.((it) =>
                        it?.project_name?.includes(modalprops.filter ?? '')
                      )
                      ?.map((it) => it.id)
                  : []
              }
              strategy={rectSortingStrategy}
            >
              {value &&
                value
                  ?.filter?.((it) =>
                    it?.project_name?.includes(modalprops.filter ?? '')
                  )
                  ?.map?.((it, i) => {
                    return (
                      <ActionAreaCard
                        value={value}
                        setValue={setValue}
                        setmodal={setmodal}
                        key={it.id}
                        {...it}
                      />
                    );
                  })}
            </SortableContext>
            {value &&
              value?.filter?.((it) =>
                it?.project_name?.includes(modalprops.filter ?? '')
              )?.length == 0 && <Empty />}
          </Grid>
        </DndContext>
      </div>
      <Modal
        {...modalprops}
        onClose={() => {
          setmodal((s) => ({
            ...s,
            open: false,
          }));
        }}
        onOk={() => {
          if (modalprops.title === '搜索') {
            setmodal((s) => ({
              ...s,
              open: false,
              filter: s.search,
            }));
          } else {
            if (!ref.current.submit?.project_name) {
              return;
            }
            if (
              value.some(
                (it) => it.project_name == ref.current.submit?.project_name
              )
            ) {
              dispatch(
                change({
                  open: true,
                  message: '已存在的项目名称!',
                  severity: 'error',
                })
              );
              return;
            }
            const newvalue = [
              ...value,
              {
                ...ref.current.submit,
                created_at: dayjs().format('YYYY-MM-DD HH:mm:ss'),
                id: dayjs().valueOf(),
              },
            ];
            setValue(newvalue);
            if (dragpath) {
              localStorage.setItem(ref.current.submit?.project_name, dragpath);
              setdragpath(null);
            }
            setmodal((s) => ({
              open: false,
              reload: Math.random() * 10000,
            }));
          }
        }}
      >
        <div style={{ paddingTop: 12 }}>
          {modalprops.title === '搜索' ? (
            <TextField
              fullWidth
              id="outlined-basic"
              label="按项目名称搜索"
              variant="outlined"
              value={modalprops.search}
              onChange={(e) => {
                setmodal((s) => ({
                  ...s,
                  search: e.target.value,
                }));
              }}
            />
          ) : (
            <AddProject ref={ref} />
          )}
        </div>
      </Modal>
      <Fab
        className="hovereffect"
        sx={{ position: 'fixed', right: 28, bottom: 94 }}
        color="default"
        size="small"
        aria-label="add"
        onClick={() => {
          setmodal((s) => ({
            ...s,
            open: true,
            title: '搜索',
          }));
        }}
      >
        <SearchOutlined style={{ fontSize: 20, color: blue[800] }} />
      </Fab>
      <Fab
        sx={{ position: 'fixed', right: 20, bottom: 20 }}
        color="secondary"
        aria-label="add"
        onClick={() => {
          setmodal((s) => ({
            ...s,
            open: true,
            title: '添加项目',
          }));
        }}
      >
        <PlusOutlined style={{ fontSize: 20 }} />
      </Fab>
    </div>
  );
}

export default Homepage;
